package com.situ.user.controller.api;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.situ.user.bean.APIResult;
import com.situ.user.bean.Shopcart;
import com.situ.user.bean.User;
import com.situ.user.service.ShopcartService;

@RestController
@RequestMapping("/api/cart")
public class APICartController {

	@Autowired
	private ShopcartService shopcartService;

	// 根据用户找到对应的购物车
	@GetMapping("/getAll")
	public List getAll(HttpSession session) {

		User user = (User) session.getAttribute("user");

		return shopcartService.getByUserId(user.getId());
	}

	// 购物车中的商品信息
	@GetMapping("/update")
	public APIResult update(Shopcart shopcart) {
		Shopcart selectCart = shopcartService.update(shopcart);
		if (selectCart.getCount() == shopcart.getCount()) {
			return APIResult.success(null, selectCart);
		} else {
			return APIResult.fail("库存不足，修改失败", selectCart);
		}

	}

	@DeleteMapping("delete")
	public APIResult delete(Integer id) {

		Shopcart shopcart = shopcartService.remove(id);
		if (shopcart != null) {
			return APIResult.ok(shopcart);
		} else {
			return APIResult.notFound("删除失败");
		}

	}
}
